var http = require("http");
var fs = require("fs");
var url = require("url");
var path = require("path");
var express = require("express");

var mime = require("./mime").types;

var users = ["32234","rfewrew","7hy6ty"];

//创建服务器
var sever = http.createServer(function(req,res){
	
	var pathName = url.parse(req.url).pathname;
	var realPath = "index" + pathName;
	var ext = path.extname(realPath).slice(1);
	var type;
	//ext = ext ? ext : "unkown";
	type = mime[ext] || 'text/plain';
	//console.log(mime.ext);
	
	fs.exists(realPath,function(exists){
		if(!exists){
			res.writeHead(404,{'Content-Type':'text/plain'});
			res.write('The request URL' + pathName + ' was not found on this server!');
			res.end();
		}
		else{
			fs.readFile(realPath,'binary',function(err,file){
				if(err){
					res.writeHead(500,{'Content-Type':'text/plain'});
					res.end();
				}
				else{
					res.writeHead(200,{'Content-Type':type});
					res.write(file,'binary');
					res.end();
				}
			});
		}
	});
});
sever.listen(1337,localhost);
io = require("socket.io").listen(sever);


//连接服务器
io.on("connection",function(socket){
	
	//登录
	socket.on("login",function(nickname){
		if(users.indexOf(nickname) > -1){
			socket.emit("nickExists");
		}
		else{
			//保存当前客户端的用户信息
			socket.userIndex = users.length;
			socket.nickname = nickname;
			users.push(nickname);
			console.log(users);
			
			//向当前客户端发送所有用户信息
			socket.emit("loginSuccess",users);
			
			//向所有客户端发送信息(事件名称以及其他参数)
			io.sockets.emit("system",nickname,users.length,"login");
		}
	});
	
	//断线
	socket.on("disconnect",function(){
		//删除当前客户端的用户信息
		if(socket.nickname){
			users.splice(socket.userIndex,1);
			console.log(socket.nickname + " was logout");
			
			socket.broadcast.emit("system",socket.nickname,users.length,"logout");	
		}
	});
	
	//聊天
	socket.on("sendMsg",function(msg,name){
		io.sockets.emit("sendSuccess",msg,name);
	});
});

console.log("success");